package com.redwinter.logkit.sdk.parser;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.lang.Nullable;

import java.lang.reflect.Method;

/**
 * @author goudadong
 * @description 日志操作计算
 * @datetime 2021-12-14 16:05
 * @email 2360564660@qq.com
 **/
public class LogOperationExpressionEvaluator extends LogExpressionEvaluator {


    public EvaluationContext createEvaluationContext(Method method, Object[] args, Object target, Class<?> targetClass, Method targetMethod,
                                                     @Nullable Object result, @Nullable BeanFactory beanFactory, String errorMsg) {
        // 创建根对象
        final LogExpressionRootObject rootObject = new LogExpressionRootObject(method, args, target, targetClass);
        // 创建上下文
        final LogEvaluationContext evaluationContext =
                new LogEvaluationContext(rootObject, method, args, getParameterNameDiscoverer(), result, errorMsg);
        if (beanFactory != null) {
            evaluationContext.setBeanResolver(new BeanFactoryResolver(beanFactory));
        }
        return evaluationContext;
    }

    public boolean condition(String conditionExpression, EvaluationContext evalContext) {
        return (Boolean.TRUE.equals(getExpression(conditionExpression).getValue(
                evalContext, Boolean.class)));
    }

    public <T> T getValue(String expression, EvaluationContext evaluationContext, Class<T> desiredResultType) {
        Expression expr = getExpression(expression);
        return expr.getValue(evaluationContext, desiredResultType);
    }
}
